package com.broad.school_description.service.impl;

import ch.qos.logback.classic.pattern.CallerDataConverter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.broad.school_description.dao.GetSchoolExample;
import com.broad.school_description.dao.GetUrl;
import com.broad.school_description.pojo.*;
import com.broad.school_description.service.GetSchoolExampleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.jdbc.exceptions.MySQLQueryInterruptedException;
import io.lettuce.core.RedisException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class GetSchoolExampleServiceImpl implements GetSchoolExampleService {
    @Autowired
    private GetSchoolExample getSchoolExample;
    @Autowired
    private GetUrl getUrl;
    @Autowired
    RedisTemplate<String, String> redisTemplate;


    /**
     * 获取所有数据封装DataVO
     * 并使用Redis 进行缓存
     * all_data_count:num
     * all_data:data
     */
    public String getSchoolExampleData(Integer page, Integer limit) {
        ResultMsg<SchoolExample> schoolExampleResultMsg = new ResultMsg<>();
        Integer count;
        List<SchoolExample> result;
        Integer startId = (page - 1) * limit;
        Integer endId = page * limit;
        try {
            // 查询redis
            String allData = redisTemplate.opsForValue().get("all_data_" + page + limit);
            // 不在redis
            if (allData == null || allData.length() < 1) {
                count = getSchoolExample.getSchoolExampleAllCount();
                result = getSchoolExample.getSchoolExampleAllAccId(startId,endId);
                // 缓存 成json格式保存
                String str = JSON.toJSONString(result);
                redisTemplate.opsForValue().set("all_data_" + page+"_" + limit, str);
                redisTemplate.opsForValue().set("all_data_count", count.toString(),30,TimeUnit.MINUTES);
            } else {
                // 解析
                result = JSON.parseArray(allData, SchoolExample.class);
                String allDataCount = redisTemplate.opsForValue().get("all_data_count"+ page+"_" + limit);
                if (allDataCount == null || allDataCount.length() < 1) {
                    count = getSchoolExample.getSchoolExampleAllCount();
                    redisTemplate.opsForValue().set("all_data_count", count.toString(),30,TimeUnit.MINUTES);
                }
                else
                    count = Integer.parseInt(allDataCount);
            }
            // 发生redis 异常，重新查库
        } catch (RedisException e){
            System.out.println(e.getMessage());
            count = getSchoolExample.getSchoolExampleAllCount();
            result = getSchoolExample.getSchoolExampleAllAccId(startId,endId);
        }

        schoolExampleResultMsg.setCode(0);
        schoolExampleResultMsg.setCount(count);
        schoolExampleResultMsg.setMsg("");
        schoolExampleResultMsg.setData(result);
        return JSON.toJSONString(schoolExampleResultMsg);
    }

    /**
     * 获取筛选查询封装DataVO
     */
    public DataVo<SchoolExample> getSelSchoolExampleData(Integer page, Integer limit, String nationArea, String major) {

        // 动态sql修改
        DataVo<SchoolExample> dataVo = new DataVo<>();
        dataVo.setCode(0);
        dataVo.setCount(getSchoolExample.getSelSchoolExampleCount(nationArea, major));
        dataVo.setMsg("");
        PageHelper.startPage(page, limit);
        List<SchoolExample> result = getSchoolExample.getSelSchoolExample(nationArea, major);
        PageInfo<SchoolExample> pageInfoSchool = new PageInfo<>(result);
        dataVo.setData(result);
        return dataVo;


    }

    /**
     * 获取url，并使用redis缓存
     * id:url
     */
    public String getUrlService(Integer id) {
        if (id == null || id < 0) {
            return "";
        } else {
            String url = "";
            try {
                // 先查redis
                url = redisTemplate.opsForValue().get(id.toString());
                // redis不存在
                if (url == null || url.length() < 1) {
                    // 查数据库
                    url = getUrl.getUrl(id);
                    // 更新redis
                    redisTemplate.opsForValue().set(id.toString(), url, 100, TimeUnit.SECONDS);
                }
                // 存在，直接返回
                return url;
            } catch (Exception e) {
                System.out.println(e.getMessage());
                url = getUrl.getUrl(id);
            }
            return url;
        }
    }


}
